var config = require('../../script/config');
var publicApi = require('../../script/public.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getOpenId();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  getOpenId() {
    const that = this;
    if (app.globalData.openid == null || app.globalData.openid == "") {
      wx.login({
        success(res) {
          if (res.code) {
            publicApi.WxAuthCode(res.code).then(res1 => {
              if (res1.code === 200) {
                app.globalData.openid = res1.data.openId;
                if (res1.data.accessToken == null || res1.data.refreshToken == null) {
                  wx.showModal({
                    title: '',
                    showCancel: false,
                    content: '当前未绑定用户，请先绑定用户',
                    success(resf) {
                      if (resf.confirm) {
                        wx.reLaunch({
                          url: "../login/login"
                        })
                      }
                    }
                  })
                } else {
                  app.globalData.token = res1.data.accessToken;
                  app.globalData.xtoken = res1.data.refreshToken;
                  wx.setStorageSync(config.storageKey.token, res1.data.accessToken);
                  wx.setStorageSync(config.storageKey.xtoken, res1.data.refreshToken);
                  that.GetInfo();
                }
              }else{
                wx.showToast({
                  icon: 'none',
                  title: res.info,
                  duration: config.toast.duration
                })
              }
            });
          }else{
            wx.showToast({
              icon: 'none',
              title: '登录失败',
              duration: config.toast.duration
            })
          }
        },
        fail(res){
          wx.showToast({
            icon: 'none',
            title: res.errMsg + res.errno,
            duration: config.toast.duration
          })
        }
      })
    }else{
      wx.switchTab({
        url: '../index/index'
      })
    }
  },
  GetInfo: function () {
    publicApi.GetInfo().then(res => {
      if(res.code === 200){
        app.globalData.userInfo = res.data;
        wx.setStorageSync(config.storageKey.userinfo, res.data);
        wx.switchTab({
          url: '../index/index'
        })
      }else{
        wx.showToast({
          icon: 'none',
          title: res.info,
          duration: config.toast.duration
        })
      }
    })
  },
})